package com.atguigu.edu.realtime.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.async.RedisAsyncCommands;
import org.apache.commons.lang3.StringUtils;

public class RedisUtil {

    //获取支持异步操作的Redis客户端
    public static StatefulRedisConnection<String,String> getAsyncRedisConnection(){
        // 连接到 redis 的0号库
        RedisClient redisClient = RedisClient.create("redis://hadoop103:6379/0");
        return redisClient.connect();

    }

    //关闭支持异步操作的Redis客户端
    public static void closeAsyncRedisConnection(StatefulRedisConnection<String,String> asyncRedisConn){
        if(asyncRedisConn != null && asyncRedisConn.isOpen()){
            asyncRedisConn.close();
        }
    }

    //以异步的方式 从Redis中查询维度数据
    public static JSONObject asyncGetDimInfo(StatefulRedisConnection<String,String> asyncRedisConn, String redisKey){
        RedisAsyncCommands<String, String> redisAsyncCommands = asyncRedisConn.async();
        try {
            String dimInfoStr = redisAsyncCommands.get(redisKey).get();
            if(StringUtils.isNotEmpty(dimInfoStr)){
                return JSON.parseObject(dimInfoStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //以异步的方式向Redis写入数据
    public static void asyncWriteDim(StatefulRedisConnection<String,String> asyncRedisConn,
                                     String redisKey,
                                     JSONObject dimJsonObj){
        RedisAsyncCommands<String, String> asyncCommands = asyncRedisConn.async();
        asyncCommands.setex(redisKey,3600*24,dimJsonObj.toJSONString());
    }
    //异步删除数据
    public static void deleteDim (StatefulRedisConnection<String,String> asyncRedisConn,
                                  String redisKey){
        RedisAsyncCommands<String, String> async = asyncRedisConn.async();
        async.del(redisKey);
    }
}
